/*
 *   Copyright 1999-2015 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.ai.aicontact.config;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.ai.aicontact.common.util.K;

/**
 * @version v 1.0 on 2015/11/5 14:32
 * @auther william.xu
 */

//@Configuration
//@EnableTransactionManagement
@EnableConfigurationProperties({ DataSourceDefaultProperties.class })
public class DataSourceConfig implements EnvironmentAware {

	@Autowired
	private DataSourceDefaultProperties dataSourceDefaultProperties;
	private Environment environment; 
	// 从application.yml中读取资源
	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment; 
	}

	@Bean(initMethod = "init", destroyMethod = "close",name="dataSource")
	@Primary
	// 必需，否则报错：No qualifying bean of type [javax.sql.DataSource] is defined:
	// expected single matching bean but found 2: kettleDataSource,dataSource
	public DataSource defaultDataSource() throws Exception {
		dataSourceDefaultProperties.setPassword(K.k_s(this.dataSourceDefaultProperties.getPassword()));
		Map properties = transBean2Map(dataSourceDefaultProperties);
		return build(properties);
	}

	public static DataSource build(Map properties) {
		DataSource dataSource = new com.alibaba.druid.pool.DruidDataSource();
		MutablePropertyValues mpv = new MutablePropertyValues(properties);
		new RelaxedDataBinder(dataSource).bind(mpv);

		return dataSource;
	}

	public static Map<String, Object> transBean2Map(Object obj) {

		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属�??
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);

					map.put(key, value);
				}
			}
		} catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}

		return map;

	}

	// @Autowired
	// private DataSource dataSource;

	@Bean(name="sessionFactory")
	public SessionFactory defaultSessionFactory() throws Exception {
		LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
		bean.setDataSource(dataSource);
		Properties hibernateProperties = new Properties();
		hibernateProperties.put("hibernate.hbm2ddl.auto", "none");
		hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
		hibernateProperties.put("hibernate.show_sql", "true");
		hibernateProperties.put("hibernate.format_sql", "true");
		hibernateProperties.put("hibernate.use_sql_comments", "false");
		bean.setHibernateProperties(hibernateProperties);
		bean.setPackagesToScan("com.ai.aicontact.*.entity.*");
		return bean.getObject();
	}

	@Autowired
	private DataSource dataSource;
	@Autowired
	private SessionFactory sessionFactory;

	// txManager事务开启
	@Bean
	public HibernateTransactionManager txManager() throws Exception {
		HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
		hibernateTransactionManager.setSessionFactory(sessionFactory);
		return hibernateTransactionManager;
	}

}